import dataPreferences from '@ohos.data.preferences';
import { ValueType } from '@ohos.data.ValuesBucket';
import { Context } from '@ohos.abilityAccessCtrl';

export namespace cm {

  export const DEVICE_ID = "device_id";

  export const NONCE = "nonce";

  export const ACCESS_TOKEN = "access_token";

  export const ACCESS_SECRET = "access_secret";

  const SHARED_KEY: string = "shared";

  // 首页- 隐私政策询问，逻辑为新安装后出现
  export const OPEN_PRIVACY: string = "privacy_agree"

  export class CacheManager {
    //Preference本身做了内存缓存
    static context: Context;

    static async initClass(context: Context): Promise<void> {
      CacheManager.context = context;
      if (!CacheManager._sharedInstance) {
        CacheManager._sharedInstance = new CacheManager(SHARED_KEY);
        await CacheManager._sharedInstance.init();
      }
    }

    private preference: dataPreferences.Preferences
    private name: string;
    private static _sharedInstance: CacheManager;

    public static sharedInstance() {
      return CacheManager._sharedInstance;
    }

    //创建实例后,不能直接使用,因为是异步初始化好的.
    //可以使用首屏进行处理,在这里进行所有的初始化操作.
    constructor(name: string) {
      this.name = name;

    }

    async init() {
      let preferences = await dataPreferences.getPreferences(CacheManager.context, this.name);
      this.preference = preferences;
    }

    /**
     * TIPS:
     * 必须调用flush否则不会保存成功.
     * @param key
     * @param object
     */
    save(key: string, object: ValueType) {
      this.preference.putSync(key, object);
      this.preference.flush();
    }

    remove(key: string) {
      this.preference.deleteSync(key);
      this.preference.flush();
    }

    saveJson(key: string, object: object) {
      this.preference.putSync(key, `${JSON.stringify(object)}`);
      this.preference.flush();
    }

    fetch(key: string): string {
      return this.fetchString(key);
    }

    saveString(key: string, object: string) {
      this.preference.putSync(key, object);
      this.preference.flush();
    }

    fetchString(key: string): string {
      let val = this.preference.getSync(key, "");
      return val.toString();
    }

    fetchNumber(key: string): number | null {
      let val: string = this.fetchString(key);
      if (val.length == 0) {
        return null;
      }
      let ret = Number.parseInt(val);
      if (Number.isNaN(ret)) {
        return null;
      }
      return ret;
    }

    fetchBool(key: string, def: boolean): boolean {
      let val = this.preference.getSync(key, def) as boolean;
      return val.valueOf();
    }
  }
}